package com.china08.yxyapi.api.manage.tec.teaching.lecture.catalog;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.lecture.YxyLectureCatalog;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.lecture.YxyLectureCatalogRepository;

import io.swagger.annotations.ApiOperation;

/**
 * 老师 ---备授课--切换备授课目录之后，将此目录更改为缺省目录
 * 
 */
@CrossOrigin
@RestController
public class LectureUptDefaultCatalogController extends YxyApiBaseController {

    @Autowired
    private YxyLectureCatalogRepository yxyLectureCatalogRepository;

    @ApiOperation(value = "老师 ---备授课--切换备授课目录之后，将此目录更改为缺省目录")
    @RequestMapping(value = "/api_yw/manage/tec/teaching/lecture/catalog/upt/default", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel req,
            RespModel respModel) {

        String userId = getProfile(request, response).getId();
        String schoolId = getProfile(request, response).getSchoolId();

        Assert.notNull(StringUtils.defaultIfBlank(userId, null), "用户id必须");
        Assert.notNull(StringUtils.defaultIfBlank(schoolId, null), "学校id必须");

        respModel = new RespModel();

        // 先查询出本人所有维护的目录，将传递过来的id设置为缺省，其他的设置为非缺省
        List<YxyLectureCatalog> yxyLectureCatalogs = yxyLectureCatalogRepository.findByUserIdAndSchoolId(userId,
                schoolId);
        if (yxyLectureCatalogs != null && !yxyLectureCatalogs.isEmpty()) {
            for (YxyLectureCatalog cataLog : yxyLectureCatalogs) {
                if (cataLog.getId().equals(req.id)) {
                    cataLog.setIsDefault(1);
                } else {
                    cataLog.setIsDefault(0);
                }
                yxyLectureCatalogRepository.save(cataLog);
            }
        }

        respModel.setCode(1);
        return respModel;
    }

    protected static class ReqModel extends YxyApiReqModel {

        /**
         * 目录id
         */
        public String id;

        @Override
        public void autoCheck() {
            Assert.notNull(StringUtils.defaultIfBlank(id, null), "id不能为空");
        }

    }

    protected static class RespModel extends YxyApiRespModel {

    }
}
